#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Filename: csa.py
# Date: 2009/09/30
# Desc: 检测服务器是否当机,是则发送短信
import os,urllib,ConfigParser,time

def checkServerAlive(ifp):
	""" 检查服务器是否宕机
	"""
	commend = "ping -c3 %s" %(ifp)
	re = os.system( commend )
	return re
	
def sendFetion(me,pwd,to,message,uri):
	""" 发送飞信
	"""
	params = urllib.urlencode({'me':me,'pwd':pwd,'to':to,'msg':message})
	url = uri+'?'+params
	ss = urllib.URLopener()
	ss.open( url )
	ss.close()
	
def main():
	""" 读取配置，检测Server，发送短信
	"""
	# 1.读取配置文件
	cf = ConfigParser.ConfigParser()
	cf.read("csa.conf")
	
	# 2.读取Fetion配置
	fetion_me =cf.get("fetion", "fetion_me")
	fetion_pwd=cf.get("fetion", "fetion_pwd")
	fetion_to=cf.get("fetion", "fetion_to")
	fetion_uri=cf.get("fetion", "fetion_uri")
	time_step=cf.getint("fetion", "time_step")
	
	while 1:
		# 2.循环读取扫描服务器
		sections = cf.sections()
		for section in sections:
			type = cf.getint(section, "entype")
			if type == 1:
				ifp = cf.get(section, "ifp")
				desc = cf.get(section, "desc")
				re = checkServerAlive(ifp)
				if re != 0: #ping不通,发送短信
					now = time.strftime( '%Y-%m-%d %H:%m:%S' ,time.localtime() )
					message = "%s \n\tServer Down: %s \n\tDesc: %s" %(now,ifp,desc)
					sendFetion(fetion_me,fetion_pwd,fetion_to,message,fetion_uri)
		time.sleep(time_step)

if __name__ == "__main__":
	main()

